<template>
	<view>
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="content">信息群发</block>
		</cu-custom>
		<l-file ref="lFile" :logo="logo" @up-success="onSuccess"></l-file>
		<view class="padding">
			<button @tap="onUpload">上传excel</button>
			<!-- <button @tap="xun([1,2,3,4,5],0)">测试</button> -->
		</view>
		<view class="upDataS" v-if="upDataS">
			<view class="">
				导入列表共{{bodys.length}}条
			</view>
			<view class="title">表头数据：</view>
			<view v-if="headers.length > 0">
				<!-- <uni-tag :text="item" v-for="(item, i) in headers" :key="i"></uni-tag> -->
				<view class="tab" @click="onTab(item)" v-for="(item, i) in headers" :key="i"> {{item}}</view>
			</view>
			<view class="">
				<view class="title">短信模板：</view>
				<textarea class="textarea" @blur="bindTextAreaBlur" :value="textarea" placeholder-style="color:#F76260"
					maxlength="70" placeholder="比如: 你好,${名字}!" />
			</view>
			<view v-if="headers.length > 0">
				<view class="title">
					选择目标手机号:
				</view>
				<view class='padding-sm flex flex-wrap'>
					<view class="padding-xs" v-for="(item,index) in List" :key="index" v-if="item.name!='white'">
						<view class='cu-tag line-black' @click="delList(index)">{{item}} <text
								class="cuIcon-close"></text></view>
					</view>
					<picker class="picker padding-xs" @change="bindPickerChange" mode="selector" :value="index"
						:range="headers">
						<view class='cu-tag line-black'>添加</view>
					</picker>
				</view>

			</view>
			<view class="">
				成功条数：{{ss.length}} 失败条数： {{err.length}} 手机号码相同数：{{xiangtongshu}}
			</view>
			<button @tap="onSend" :disabled="disabled">发送</button>
			<button type="default" v-if="disabled" @click="tableToExcel">导出</button>
		</view>
	</view>
</template>

<script>
	import configService from '@/common/service/config.service.js'
	import {
		formatNumber,
		formatDateThis,
		getUnixTime
	} from "@/common/util/dateUtil.js"
	export default {
		data() {
			return {
				time: new Date(),
				disabled: false,
				index: 0,
				upDataS: false,
				headers: [],
				textarea: "你好！${姓名}！你的手机号码是${病案号}",
				phone: "现电话",
				bodys: [],
				ss: [],
				err: [],
				sendBug: "",
				SendData: [],
				sendNumber: 0,
				SendDataArr: [],
				List: ["现电话", "单位电话", "联系人电话"],
				phoneList: [],
				xiangtongshu: 0,
				logo: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F00%2F07%2F155788a6d8a5c42.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619847627&t=2da40b583002205c204d980b54b35040',
			}
		},
		onLoad() {

		},
		watch: {},
		methods: {
			delList(i) {
				this.List.splice(i, 1);

			},
			bindPickerChange(e) {
				console.log('picker发送选择改变，携带值为', e.target.value)
				this.index = e.target.value;
				this.phone = this.headers[this.index]
				this.List.push(this.phone)
			},
			// 上传记录数据
			// newDB() {
			// 	this.$http.post("/logData", this.SendData).then((e) => {
			// 		console.log(e)
			// 	})
			// },
			onTab(e) {
				this.textarea = this.textarea + '${' + e + '}'
			},
			bindTextAreaBlur: function(e) {
				console.log(e.detail.value)
				this.textarea = e.detail.value
			},
			/* 上传 */
			onOpenNameDoc(path = '') {
				if (!path) {
					return;
				}
				/* 打开文件 */
				this.$refs.lFile.open(path);
			},
			/* 上传 */
			onUpload() {
				/**
				 * currentWebview: 当前webview
				 * url：上传接口地址
				 * name：附件key,服务端根据key值获取文件流，默认file,上传文件的key
				 * header: 上传接口请求头
				 */
				this.$refs.lFile.upload({
					// #ifdef APP-PLUS
					// nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
					currentWebview: this.$mp.page.$getAppWebview(),
					// #endif
					url: configService.apiUrl + '/uploadxlsx', //替换为你的
					name: 'file'
					// body参数直接写key,value,如：
					// key1: 'value1',
					// key2: 'value2',
				});
			},
			onSuccess(res) {
				console.log('上传成功回调', JSON.stringify(res));
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				this.$http.get("/excels/" + res.id).then((e) => {
					console.log(e)
					if (e.statusCode == 200) {
						// this.SendData = e.data.excel;
						this.headers = e.data.excel.headers;
						this.bodys = e.data.excel.body;
						this.upDataS = true;
						uni.hideLoading()
					}
				})
				// this.SendData = res;
				// this.headers = res.headers;
				// this.bodys = res.body;
				// this.upDataS = true;
				// uni.showToast({
				// 	title: JSON.stringify(res),
				// 	icon: 'none'
				// })
			},
			checkPhone(phone) {
				return /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(phone)
				// alert("手机号码有误，请重填");  
			},
			gotoAppPermissionSetting: function() {
				permision.gotoAppPermissionSetting()
			},
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID)
				var strStatus
				if (result == 1) {
					strStatus = "已获得授权"
				} else if (result == 0) {
					strStatus = "未获得授权"
				} else {
					strStatus = "被永久拒绝权限"
				}
				uni.showModal({
					content: permisionID + strStatus,
					showCancel: false
				});
			},
			onSend() {

				uni.showLoading({
					title: `发送中`,
					mask: true
				});
				this.disabled = true;
				// uni.onTabBarMidButtonTap(() => {
				// 	plus.android.requestPermissions(['android.permission.SEND_SMS'], (e) => {
				// 		console.log(e)
				// 	})
				// })
				// this.requestAndroidPermission('android.permission.SEND_SMS')
				console.log(this.textarea);
				var that = this;
				var to = that.bodys;
				// console.log(to)
				// that.SendData.body = to.map((e) => {
				// 	var msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
				// 	var phone = e[that.phone];
				// 	if (that.checkPhone(phone) || phone == 10010) {
				// 		msg.to = [phone];
				// 		var text = that.textarea;
				// 		that.headers.map((el) => {
				// 			var reg = "/\\${" + el + "}/g";
				// 			// debugger
				// 			// var reg = new RegExp(eval(text) , "g" );
				// 			// console.log(e[el])
				// 			text = text.replace(eval(reg), e[el]);
				// 		})
				// 		msg.body = text;
				// 		console.log(msg.body)
				// 		msg.silent = true;
				// 		e.text = text;
				// 		plus.messaging.sendMessage(msg, function() {
				// 			e.code = 'success'
				// 			that.ss.push(e)
				// 			// plus.nativeUI.closeWaiting();
				// 		}, function(el) {
				// 			console.log(el)
				// 			if (el.code == 13) {
				// 				that.sendBug = "短信权限没设置，需要手动打开"
				// 			}
				// 			that.err.push(e);
				// 			// plus.nativeUI.closeWaiting();
				// 		});
				// 	} else {
				// 		e.code = 'err';
				// 		e.text = '手机号码错误！'
				// 		that.err.push(e);
				// 	}
				// 	return e;
				// })
				this.phoneList = [];
				this.SendData = [];
				this.xun(to, 0);
				// this.newDB()
				// console.log(`短信发送完成！失败${err.length}条!`)
				// plus.nativeUI.alert(`短信发送完成！成功${ss.length}条！失败${err.length}条`);
			},
			// 发送短信
			sendSMS(data) {
				var that = this;

				// #ifdef APP-PLUS
				var msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);

				msg.to = [data.phone];

				msg.body = data.text;
				console.log(msg.body)
				msg.silent = true;
				plus.messaging.sendMessage(msg, function() {
					data.code = 'success';
					that.$http.post("/logData", {
						body: data
					}).then((el) => {
						console.log(el)
						if (el.statusCode == 200) {
							that.ss.push(data);
							that.SendData.push(data);
							that.sendNumber++;
							console.log(that.sendNumber)
							// i++;
							// that.xun(arr, i)
							// if (pi == that.List.length - 1) {
							// 	if (that.sendNumber % 30 == 0) {
							// 		setTimeout(function() {
							// 			i++;
							// 			that.xun(arr, i)
							// 		}, 15000)
							// 	} else {
							// 		setTimeout(function() {
							// 			i++;
							// 			that.xun(arr, i)
							// 		}, 4000)
							// 	}
							// }
						}
					})
				}, function(el) {
					console.log(el)
					if (el.code == 13) {
						// that.sendBug = "短信权限没设置，需要手动打开"
						uni.hideLoading()
						uni.showToast({
							title: '短信权限没设置，需要手动打开',
							icon: "none",
							duration: 1000
						});
					}
					// that.err.push(e);
					// plus.nativeUI.closeWaiting();
				});
				// #endif
			},
			// 处理完再执行下一条
			xun(arr, i) {
				var that = this;
				if (arr.length > i) {
					var e = arr[i];
					e.时间段 = that.time;
					that.List.map((pEl, pi) => {
						// var msg = {};
						var phone = e[pEl]; //找出一行中的手机号码
						if (that.checkPhone(phone) || phone == 10010) {
							if (that.phoneList.includes(phone)) { //判断是否发送过相同的手机号码
								that.xiangtongshu++;
								// if (pi == that.List.length - 1) {
								// 	i++;
								// 	that.xun(arr, i)
								// }
								return null
							}

							that.phoneList.push(phone);
							var text = that.textarea;
							that.headers.map((el) => {
								var reg = "/\\${" + el + "}/g";
								// debugger
								// var reg = new RegExp(eval(text) , "g" );
								// console.log(e[el])
								text = text.replace(eval(reg), e[el]);
							})
							that.SendDataArr.push({
								phone,
								text
							})

							// plus.nativeUI.closeWaiting();
						} else {
							this.$http.post("/logData", {
								body: e
							}).then((el) => {
								console.log(el)
								if (el.statusCode == 200) {
									e.code = 'err';
									e.text = '手机号码错误！'
									that.err.push(e);
									that.SendData.push(e)
									if (pi == that.List.length - 1) {
										// i++;
										// that.xun(arr, i)
									}
								}
							})
						}
					})
					// return e;
					i++;
					that.xun(arr, i)
				} else {
					console.log(that.phoneList)
					// for (let ind = 1; ind < that.SendDataArr.length; ind++) {
					// 	setTimeout(() => {
					// 		that.sendSMS(that.SendDataArr[ind])
					// 	}, 1000)
					// }
					var length = that.SendDataArr.length;
					var timeout = null;
					var index = 0;

					function play() {
						clearTimeout(timeout);
						timeout = setTimeout(function() {
							if (index === length) {
								uni.hideLoading()
								return;
							}
							that.sendSMS(that.SendDataArr[index])
							play();
							index++;
						}, 2000);
						console.log(20)
					}
					play();
				}
			},
			// 导出表格
			tableToExcel() {
				//要导出的json数据
				console.log(this.SendData)
				if (this.SendData.length == 0) {
					return false
				}
				//列标题
				let worksheet = "sheet1";
				// let str = '<tr><td>姓名</td><td>电话</td><td>邮箱</td></tr>';
				let str = '<tr>';
				for (var key in this.SendData[0]) {
					str += `<td>${ key + '\t'}</td>`
				}
				str += '</tr>';
				//循环遍历，每行加入tr标签，每个单元格加td标签
				for (let i = 0; i < this.SendData.length; i++) {
					str += '<tr>';
					for (let item in this.SendData[i]) {
						//增加\t为了不让表格显示科学计数法或者其他格式
						str += `<td>${ this.SendData[i][item] + '\t'}</td>`;
					}
					str += '</tr>';
				}
				console.log(str)
				//下载的表格模板数据
				let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
			        xmlns:x="urn:schemas-microsoft-com:office:excel" 
			        xmlns="http://www.w3.org/TR/REC-html40">
			        <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
			        <x:Name>${worksheet}</x:Name>
			        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
			        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
			        </head><body><table>${str}</table></body></html>`;
				//下载模板
				this.exportFile(template);
			},
			// 导出文件到手机 fileData:要写入到文件的数据，返回参数为文档路径
			exportFile(fileData, documentName = "项目Excel文件") {
				/*
				PRIVATE_DOC: 应用私有文档目录常量
				PUBLIC_DOCUMENTS: 程序公用文档目录常量
				*/
				let that = this;
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {

					let rootObj = fs.root;
					let fullPath = rootObj.fullPath;
					// let reader = rootObj.createReader();
					// console.log(reader);
					// reader.readEntries((res)=>{
					//     console.log(res); //这里拿到了该目录下所有直接文件和目录
					// },(err)=>{console.log(err);})
					console.log("开始导出数据********");
					// 创建文件夹
					rootObj.getDirectory(documentName, {
						create: true
					}, function(dirEntry) {
						//获取当前的年月继续创建文件夹
						let date = new Date();
						let year = date.getFullYear();
						let month = date.getMonth() + 1;
						dirEntry.getDirectory(`${year}年${month}月`, {
							create: true
						}, function(dirEntry2) {
							// 创建文件,防止重名
							let fileName = "excel" + getUnixTime(formatDateThis(
								new Date()));
							console.log(fileName);
							dirEntry2.getFile(`${fileName}.xlsx`, {
								create: true
							}, function(fileEntry) {
								fileEntry.createWriter(function(writer) {
									writer.onwritestart = (e) => {
										uni.showLoading({
											title: "正在导出",
											mask: true
										})
									}

									//  /storage/emulated/0指的就是系统路径
									let pathStr = fullPath.replace(
										"/storage/emulated/0", "");
									writer.onwrite = (e) => {
										// 成功导出数据;
										uni.hideLoading();
										setTimeout(() => {
											uni.showToast({
												title: "成功导出，`文件位置：${pathStr}/${documentName}/${year}年${month}月`",
												icon: "success"
											})
											// that.successTip =
											// 	`文件位置：${pathStr}/${documentName}/${year}年${month}月`;
										}, 500)

									};
									// 写入内容;
									writer.write(fileData);
								}, function(e) {
									console.log(e.message);
									uni.hideLoading()
								});
							});
						})

					});
				})
			}
		}
	}
</script>

<style lang="scss">
	button {
		margin: 15px;
		color: #007AFF;
	}

	.upDataS {
		margin: 15px;

		.title {
			font-size: 16px;
			color: #DD524D;
			margin: 10px 0;
		}

		.textarea {
			width: 100%;
			padding: 2px;
			border: 1px solid #555555;
			font-size: 14px;
			border-radius: 4px;
		}

		.tab {
			padding: 4px 10px;
			margin-left: 10px;
			margin-bottom: 10px;
			border: 1px solid #0081FF;
			font-size: 14px;
			border-radius: 4px;
			display: inline-block;
		}

		.picker {
			padding-left: 20px;
			font-size: 14px;
			color: #0081FF;
			margin-bottom: 20px;
		}
	}
</style>
